<template>
    <div class="login-vue" :style="bg">
        <b-container class="bv-example-row row-box">
            <b-row align-h="center">
                <b-col cols="12" sm="12" md="5" lg="5" class="register-contain">
                    <div class="logo-info">
                        <router-link to="/"><img :src="logo" alt=""></router-link>
                    </div>
                    <div class="register-item">
                        <Tabs value="name1">
                            <TabPane label="手机注册" name="name1">
                                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
                                    <FormItem prop="identifier">
                                        <Input v-model="formValidate.identifier" placeholder="您的注册手机号" />
                                    </FormItem>
                                    <FormItem prop="code">
                                        <Row>
                                            <i-col span="18">
                                                <Input type="text" v-model="formValidate.code" placeholder="请输入验证码" />
                                            </i-col>
                                            <i-col span="5" offset="1">
                                                <Button @click="sendPhoneCode" :disabled="isDisable">{{send}}</Button>
                                            </i-col>
                                        </Row>
                                    </FormItem>
                                    <FormItem prop="credential">
                                        <Input type="password" v-model="formValidate.credential" placeholder="密码不少于6位"/>
                                    </FormItem>
                                    <FormItem>
                                        <Button type="primary" @click="saveByPhone('formValidate')" long>注册</Button>
                                    </FormItem>
                                </Form>
                                <div class="extra">
                                    <p>
                                        <span>已经拥有账户?</span><router-link to="/login">登录</router-link>
                                    </p>
                                </div>
                            </TabPane>
                            <TabPane label="邮箱注册" name="name2">
                                <Form ref="formValidateEmail" :model="formValidateEmail" :rules="ruleValidateEmail">
                                    <FormItem prop="email">
                                        <Input v-model="formValidateEmail.email" placeholder="您的注册邮箱号" />
                                    </FormItem>
                                    <FormItem prop="code">
                                        <Row>
                                            <i-col span="18">
                                                <Input type="text" v-model="formValidateEmail.code" placeholder="请输入验证码" />
                                            </i-col>
                                            <i-col span="5" offset="1">
                                                <Button @click="sendEmailCode" :disabled="isDisableEmail">{{sendEmail}}</Button>
                                            </i-col>
                                        </Row>
                                    </FormItem>
                                    <FormItem prop="credential">
                                        <Input type="password" v-model="formValidateEmail.credential" placeholder="密码不少于6位"/>
                                    </FormItem>
                                    <FormItem>
                                        <Button type="primary" @click="saveByEmail('formValidateEmail')" long>注册</Button>
                                    </FormItem>
                                </Form>
                                <div class="extra">
                                    <p>
                                        <span>已经拥有账户?</span><router-link to="/login">登录</router-link>
                                    </p>
                                </div>
                            </TabPane>
                        </Tabs>
                    </div>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>

<script>
export default {
  name: 'register',
  data () {
    return {
      logo: require('../assets/imgs/logo2.png'),
      msg: '',
      isDisable: false,
      send: 'send',
      isDisableEmail: false,
      sendEmail: 'send',
      // 手机号验证
      formValidate: {
        identifier: '',
        code: '',
        credential: ''
      },
      ruleValidate: {
        identifier: [
          { required: true, message: '手机号不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ],
        credential: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { type: 'string', min: 6, message: '请注意密码不少于6位', trigger: 'blur' }
        ]
      },
      // 邮箱验证
      formValidateEmail: {
        email: '',
        code: '',
        credential: ''
      },
      ruleValidateEmail: {
        email: [
          { required: true, message: '邮箱号不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ],
        credential: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { type: 'string', min: 6, message: '请注意密码不少于6位', trigger: 'blur' }
        ]
      },
      bg: {}
    }
  },
  created () {
    this.bg.backgroundImage = 'url(' + require('../assets/imgs/bg0' + new Date().getDay() + '.jpg') + ')'
  },
  methods: {
    // 发送短信验证码之前判断 identifier 是否存在
    sendPhoneCode () {
      this.$axios({
        url: 'userLoginAuths/checkIdentifier',
        method: 'get',
        params: {
          identifier: this.formValidate.identifier
        }
      }).then(res => {
        // 为 true 发送验证码
        if (res.data === true) {
          this.$axios({
            url: 'userLoginAuths/postMsg',
            method: 'get',
            params: {
              Phone: this.formValidate.identifier
            }
          }).then(result => {
            if (result.data === true) {
              // 发送验证码倒计时60s
              let second = 60
              let timer = null
              timer = setInterval(() => {
                second -= 1
                if (second > 0) {
                  this.send = `${second} s`
                  this.isDisable = true
                } else {
                  clearInterval(timer)
                  this.send = 'send'
                  this.isDisable = false
                }
              }, 1000)
            } else {
              this.$Message.error('验证码发送失败!')
            }
          })
        } else {
          this.$Message.error('此手机号有误或已被注册!')
        }
      })
    },
    // 手机号、验证码、密码提交注册新用户
    saveByPhone (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // this.$Message.success('Success!')
          // 新增用户
          this.$axios({
            url: 'userLoginAuths/saveByPhone',
            method: 'post',
            params: {
              phone: this.formValidate.identifier,
              code: this.formValidate.code,
              credential: this.formValidate.credential
            }
          }).then(res => {
            // 新增用户成功，直接登录跳转到首页
            if (res.data.code === 200) {
              this.$axios({
                url: 'userLoginAuths/loginByIdentifierAndCredential',
                method: 'get',
                params: {
                  identifier: this.formValidate.identifier,
                  credential: this.formValidate.credential
                }
              }).then(resu => {
                if (resu.data.code === 200) {
                  // 登录成功，设置用户信息
                  localStorage.setItem('user', JSON.stringify(resu.data.object))
                  localStorage.setItem('token', resu.data.token)
                  // 使用JS的形式，进行路由导航
                  this.$router.push({ path: '/' })
                }
              })
            } else if (res.data.code === 400) {
              // 验证码有误
              this.$Message.error(res.data.msg)
            }
          })
        } else {
          this.$Message.error('Fail!')
        }
      })
    },
    // 发送邮箱验证码之前判断 identifier 是否存在
    sendEmailCode () {
      this.$axios({
        url: 'userLoginAuths/checkIdentifier',
        method: 'get',
        params: {
          identifier: this.formValidateEmail.email
        }
      }).then(res => {
        // 为 true 发送邮箱验证码
        if (res.data === true) {
          this.$axios({
            url: 'userLoginAuths/sendMail',
            method: 'get',
            params: {
              email: this.formValidateEmail.email
            }
          }).then(result => {
            if (result.data === true) {
              // 发送验证码倒计时60s
              let second = 60
              let timer = null
              timer = setInterval(() => {
                second -= 1
                if (second > 0) {
                  this.sendEmail = `${second} s`
                  this.isDisableEmail = true
                } else {
                  clearInterval(timer)
                  this.sendEmail = 'send'
                  this.isDisableEmail = false
                }
              }, 1000)
            } else {
              this.$Message.error('验证码发送失败!')
            }
          })
        } else {
          this.$Message.error('此邮箱号有误或已被注册!')
        }
      })
    },
    // 邮箱号、验证码、密码提交注册新用户
    saveByEmail (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // this.$Message.success('Success!')
          // 新增用户
          this.$axios({
            url: 'userLoginAuths/saveByEmail',
            method: 'post',
            params: {
              email: this.formValidateEmail.email,
              code: this.formValidateEmail.code,
              credential: this.formValidateEmail.credential
            }
          }).then(res => {
            // 新增用户成功，直接登录跳转到首页
            if (res.data.code === 200) {
              this.$axios({
                url: 'userLoginAuths/loginByIdentifierAndCredential',
                method: 'get',
                params: {
                  identifier: this.formValidateEmail.email,
                  credential: this.formValidateEmail.credential
                }
              }).then(resu => {
                if (resu.data.code === 200) {
                  // 登录成功，设置用户信息
                  localStorage.setItem('user', JSON.stringify(resu.data.object))
                  localStorage.setItem('token', resu.data.token)
                  // 使用JS的形式，进行路由导航
                  this.$router.push({ path: '/' })
                }
              })
            } else if (res.data.code === 400) {
              // 验证码有误
              this.$Message.error(res.data.msg)
            }
          })
        } else {
          this.$Message.error('Fail!')
        }
      })
    }
  }
}
</script>

<style scoped>
.register-item{
    padding: 20px;
    background: #fff;
    border-radius: 5px;
    margin-bottom: 30px;
}
.logo-info a{
    display:block;
    text-align: center;
}
.logo-info a img{
    width: 280px;
    height: 80px;
    margin-bottom: 20px;
}
.ivu-tabs-nav-container{
    font-size: 20px !important;
}
.extra{
    text-align: center;
}
.login-vue {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
}
</style>
